////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import java.util.List;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.util.TimingLogger;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Tools.Abstract_ActivityController;
import cc.telecomdigital.tdstock.activity.groups.ForeignExchangeGroup;
import cc.telecomdigital.tdstock.activity.groups.IndexGroup;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.foreignexchange.ForeignExchangeActivity;
import cc.telecomdigital.tdstock.activity.groups.index.BMPIndexActivity;
import cc.telecomdigital.tdstock.activity.groups.index.IndexActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.BMPPortfolioActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.PortfolioActivity;
import cc.telecomdigital.tdstock.activity.groups.more.MoreActivity;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.Constants;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.Data;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.NotificationSwitch;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;

/**
 * implement customer  Tab Host
 * 
 * @author haibo
 *
 */
public class RealtimeStockActivity extends TabActivity// implements OnTabChangeListener
{
	public final static int TAB_INDEX_STOCK    = 0;
	public final static int TAB_INDEX_BOOKMARK = 1;
	public final static int TAB_INDEX_INDEX    = 2;
	public final static int TAB_INDEX_FX       = 3;
	public final static int TAB_INDEX_MORE     = 4;
	
	private final static String	TAG					= RealtimeStockActivity.class.getSimpleName();
	protected static final String	ACTION_INSTALL_SHORTCUT	= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String	EXTRA_SHORTCUT_DUPLICATE	= "duplicate";
	protected final static String	ACTIVITY_PACKAGE		= "activity.";
	protected static String		_menu_exit_app_res		= null;
	protected static String		_menu_gen_launcher_res	= null;
	public static final int		EXIT_APP				= Menu.FIRST;
	public static final int		CREATE_LAUNCHER		= Menu.FIRST + 1;
	
	//TabIndex is initially starts as 0, the realtime
	public static int       nextTabIndex             = 0;	
  //public static RealtimeStockActivity INSTANCE = null;
	//public static RealtimeStockActivity instance = null;
	public static TabHost			tabHost = null;
	public static  boolean		IS_READY_TO_CHANGE_MODE	= false;
           public static boolean IscurActivity=false;
	ITDLApplication application;
	public static  boolean 		Is_Change_Mode	= false;
	public static  boolean		IsCustomerForwardToAccountLogin = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
//		((ITDLApplication)(getApplicationContext())).SetAsActiveActivity(this);
  	//	INSTANCE = this;  //modified by haibo, 2011-06-07

		super.onCreate(savedInstanceState);
		application= (ITDLApplication) getApplicationContext();
		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(
				R.string.app_launcher);
		setContentView(R.layout.tab);
		
		setTabs();
		
		resetCurrentTab();
		ITDLApplication.GetInstance().actListController.ActivityResetToTop(getClass());
	}
	
	public static void SetTabIndex(int iNewIndex)
	{
		nextTabIndex = iNewIndex;		
		if (tabHost == null)
			return;
		
		if (iNewIndex >= tabHost.getTabWidget().getChildCount())
			return;
		
		tabHost.setCurrentTab(nextTabIndex);
	}
	
	private boolean isFristActivityClass(int ...index)
	{
		Class<?>[]  classes = { CurrentStockInfoActivity.class,  PortfolioActivity.class ,  IndexActivity.class , ForeignExchangeActivity.class ,  MoreActivity.class };
		// BMP Mode  by ouyangzhihui 2011-10-13
		if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
		{
			classes = new Class<?>[]{ BMPCurrentStockInfoActivity.class,  BMPPortfolioActivity.class ,  BMPIndexActivity.class , ForeignExchangeActivity.class ,  MoreActivity.class };
		}
		
		if(index.length < 1 ||  index[0] >= classes.length) 
		{
			// BMP Mode  by ouyangzhihui 2011-10-13
			if(BaseActivity._currActivityClass == CurrentStockInfoActivity.class 
					|| BaseActivity._currActivityClass == BMPCurrentStockInfoActivity.class 
					|| BaseActivity._currActivityClass == BMPPortfolioActivity.class
					|| BaseActivity._currActivityClass == BMPIndexActivity.class
					|| BaseActivity._currActivityClass == PortfolioActivity.class 
					|| BaseActivity._currActivityClass == IndexActivity.class 
					|| BaseActivity._currActivityClass == ForeignExchangeActivity.class 
					|| BaseActivity._currActivityClass == MoreActivity.class)
			{
				return true; // 是第一个页面，不执行reset
			}
		}
		else 
		{
			if(BaseActivity._currActivityClass == classes[index[0]]) 
			{
				return true;
			}
		}
		return false;
	}
	
	private void resetCurrentTab()
	{
		for(int i = 0; i < tabHost.getTabWidget().getChildCount(); i++)
		{
			final int index = i;
			tabHost.getTabWidget().getChildAt(i).setOnTouchListener(new OnTouchListener()
			{
				@Override
				public boolean onTouch(View v, MotionEvent event)
				{
					TDStockLog.d(TAG, "ontouch getAction="+event.getAction());
					//ActivityGroupHost_Framework groupActivity = null;
					if (event.getAction() == 0)
					{
						// 在当前tab并且不是第一个Activity才执行回到第一个Activity
						if( /*tabHost.getCurrentTab() == index && !isFristActivityClass() */ tabHost.getCurrentTab() == index &&  !isFristActivityClass(index) )
						{
							/*ActivityGroup group = null;
							Class<?> _cls = null;*/
							if (index == 0)
							{
								/*group = StockGroup.group;
								_cls = CurrentStockInfoActivity.class;*/
								
								
								Activity  curActivity;
								
								curActivity = StockGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
								StockGroup.GetActivityGroupHostControl().ActivitySwitchToTheTop(curActivity);
								
							}
							else if (index == 1)
							{
								/*group = MonitorGroup.group;
								_cls = PortfolioActivity.class;*/
								
								
								Activity  curActivity;
//								((ITDLApplication) getApplicationContext()).putString(
//										CommonDefn.ACTIVITY_CAME_FROM_KEY, PortfolioActivity.class
//												.getSimpleName());
								curActivity = MonitorGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
								MonitorGroup.GetActivityGroupHostControl().ActivitySwitchToTheTop(curActivity);
								
							}
							else if (index == 2)
							{
								/*group = IndexGroup.group;
								_cls = IndexActivity.class;*/
								
								
								Activity  curActivity;
								
								curActivity = IndexGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
								IndexGroup.GetActivityGroupHostControl().ActivitySwitchToTheTop(curActivity);
								
							}
							else if (index == 3)
							{
								/*group = ForeignExchangeGroup.group;
								_cls = ForeignExchangeActivity.class;*/
								
								Activity  curActivity;
								
								curActivity = ForeignExchangeGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
								ForeignExchangeGroup.GetActivityGroupHostControl().ActivitySwitchToTheTop(curActivity);
								
							}
							else if (index == 4)
							{
								/*group = MoreGroup.group;
								_cls = MoreActivity.class;*/
								
								
								
								Activity  curActivity;
								
								curActivity = MoreGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
								//MoreGroup.GetActivityGroupHostControl().ActivitySwitchToTheTop(curActivity);
								TDStockLog.d(TAG, "ready to forwarding to moreActivity!");
								MoreGroup.GetActivityGroupHostControl().ActivityFreeSwitch(curActivity, MoreActivity.class,  new Intent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION));
							}
							
							
							
						/*	View view = group.getLocalActivityManager().startActivity(_cls.getSimpleName(),
									new Intent(getApplicationContext(), _cls).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION)).getDecorView();
							group.setContentView(view);*/
							
							
							
							
						}
					}
					return false;
				}
			});
		}
	}

	private void setTabs()
	{
		
		/*ProgressDialog _dialog= new ProgressDialog(RealtimeStockActivity.this, Html.fromHtml("正在初始化界面<br/>請稍候...").toString());*/
		
		
		try {
			//_dialog.show();
			tabHost = getTabHost();
			TDStockLog.d(TAG, "***** setTabs EE1!");
			
			TimingLogger timings = new TimingLogger(TAG, "init tab activity...");
			//addTab(R.string.stock, R.drawable.tab_0_info,  CurrentStockInfoActivity.class);
			addTab(R.string.stock, R.drawable.tab_0_info, StockGroup.class);
			addTab(R.string.monitor, R.drawable.tab_1_info, MonitorGroup.class);
			addTab(R.string.index, R.drawable.tab_2_info, IndexGroup.class);
			addTab(R.string.foreign_exchange, R.drawable.tab_3_info,ForeignExchangeGroup.class);
			addTab(R.string.more, R.drawable.tab_4_info, MoreGroup.class);
			TDStockLog.d(TAG, "setTabs EE2!");
			
			setCurrentTab(false);
			
			timings.dumpToLog();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			/*if(_dialog != null) {
				_dialog.dismiss();
				_dialog  = null;
			}*/
			
			
		}
		
		
	}

	private void setCurrentTab(boolean flag)
	{
		// modify by ouyangzhihui(zor)  2011-07-25
		//int tabIndex = 0;
		if(((ITDLApplication) getApplicationContext()).getDataMode() != CommonDefn.DataMode.Delay)
		{
			boolean existSubscribedItems = isAnySubscribedItems(null);
			//tabIndex = existSubscribedItems ? 1 : 0;
			nextTabIndex = existSubscribedItems ? 1 : 0;
		}
		
		//This part is mandatory, since at least we want to create all controller
		//The set Current Tab makes a call to onCreate for each GroupController or Controller, which will
		//int count;
		
		/*count = tabHost.getTabWidget().getChildCount();
		for (int index = 0; index <count; index++)
		{
			if (index == tabIndex)
				continue;
			
			tabHost.setCurrentTab(index);
		}*/
		//tabHost.setCurrentTab(3);		
		tabHost.setCurrentTab(4);
//		int count;
//				
//		count = tabHost.getTabWidget().getChildCount();
//		for (int index = 0; index <count; index++)
//		{
//			if (index == nextTabIndex)
//				continue;
//			
//			tabHost.setCurrentTab(index);
//		}
		//tabHost.setCurrentTab(tabIndex));
		if(flag){
			nextTabIndex=4;
		}
		TDStockLog.d(TAG, "nextTabIndex:"+nextTabIndex+"");
		tabHost.setCurrentTab(nextTabIndex);
		
		//tabHost.setCurrentTab(tabIndex);
		initActivityGroup();
	}

	private void initActivityGroup()
	{
		StockGroup.tabHost = tabHost;
		MonitorGroup.tabHost = tabHost;
		IndexGroup.tabHost = tabHost;
		ForeignExchangeGroup.tabHost = tabHost;
		MoreGroup.tabHost = tabHost;
	}

	private boolean isAnySubscribedItems(DBHelper dbHelper)
	{
		boolean result = false;
		boolean isBuildAConnection = false;
		try
		{
			if (dbHelper == null)
			{
				dbHelper = new DBHelper(this);
				isBuildAConnection = true;
			}
			int customerId = 1;
			List<String[]> items = dbHelper
					.getSubscribeItemsByUserId(customerId);
			
			result = (items == null || items.isEmpty()) ? false : true;
		}
		catch (Exception e)
		{
			TDStockLog
					.d(
							TAG,
							e.getMessage() == null ? " unknown exception happened in isAnySubscribedItems ! "
									: e.getMessage());
		}
		finally
		{
			if (isBuildAConnection)
			{
				dbHelper.cleanup();
			}
		}
		return result;
	}

	private void addTab(int resouceTabId, int drawableId,
			Class<? extends ActivityGroup> groupActivityClass)
	{
		Intent intent = new Intent(this, groupActivityClass);
		TabHost.TabSpec spec = tabHost.newTabSpec("tab" + resouceTabId);

		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.tab_indicator, getTabWidget(), false);

		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText(resouceTabId);
		ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
		icon.setImageResource(drawableId);

		spec.setIndicator(tabIndicator);
		spec.setContent(intent);
		tabHost.addTab(spec);

	}

//	private void restoreCurrentTaskIfNeed()
//	{
//		/*if (BaseActivity._currentActivityClass != null
//				&& BaseActivity._parentActivity != null)
//		{
//			TDStockLog
//					.d(
//							TAG,
//							String
//									.format(
//											"ready to restore the task: %s and it's parent is  %s!",
//											BaseActivity._currentActivityClass
//													.getSimpleName(),
//											BaseActivity._parentActivity
//													.getClass()
//													.getSimpleName()));
//			Intent intent = new Intent(getApplicationContext(),
//					BaseActivity._currentActivityClass);
//			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//			if (BaseActivity._parentActivity instanceof StockGroup)
//			{
//
//				View currView = StockGroup.group.getLocalActivityManager()
//						.startActivity(
//								BaseActivity._currentActivityClass
//										.getSimpleName(), intent)
//						.getDecorView();
//				StockGroup.group.setContentView(currView); //modified by haibo, 2011-05-18
//				tabHost.setCurrentTab(0);
//				BaseActivity._currentActivityClass = null;
//				BaseActivity._parentActivity = null;
//				return;
//			}
//
//			if (BaseActivity._parentActivity instanceof MonitorGroup)
//			{
//				View currView = MonitorGroup.group
//						.getLocalActivityManager().startActivity(
//								BaseActivity._currentActivityClass
//										.getSimpleName(), intent)
//						.getDecorView();
//				MonitorGroup.group.setContentView(currView); //modified by haibo, 2011-05-18
//				tabHost.setCurrentTab(1);
//
//				BaseActivity._currentActivityClass = null;
//				BaseActivity._parentActivity = null;
//				return;
//			}
//
//			if (BaseActivity._parentActivity instanceof IndexGroup)
//			{
//				View currView = IndexGroup.group.getLocalActivityManager()
//						.startActivity(
//								BaseActivity._currentActivityClass
//										.getSimpleName(), intent)
//						.getDecorView();
//				IndexGroup.group.setContentView(currView); //modified by haibo, 2011-05-18
//				tabHost.setCurrentTab(2);
//
//				BaseActivity._currentActivityClass = null;
//				BaseActivity._parentActivity = null;
//				return;
//			}
//
//			if (BaseActivity._parentActivity instanceof ForeignExchangeGroup)
//			{
//				View currView = ForeignExchangeGroup.group
//						.getLocalActivityManager().startActivity(
//								BaseActivity._currentActivityClass
//										.getSimpleName(), intent)
//						.getDecorView();
//				ForeignExchangeGroup.group.setContentView(currView); //modified by haibo, 2011-05-18
//				tabHost.setCurrentTab(3);
//
//				BaseActivity._currentActivityClass = null;
//				BaseActivity._parentActivity = null;
//				return;
//			}
//
//			if (BaseActivity._parentActivity instanceof MoreGroup)
//			{
//				View currView = MoreGroup.group.getLocalActivityManager()
//						.startActivity(
//								BaseActivity._currentActivityClass
//										.getSimpleName(), intent)
//						.getDecorView();
//				MoreGroup.group.setContentView(currView); //modified by haibo, 2011-05-18
//				tabHost.setCurrentTab(4);
//
//				BaseActivity._currentActivityClass = null;
//				BaseActivity._parentActivity = null;
//				return;
//			}
//
//		
//
//		}*/
//	}

	@Override
	protected void onResume()
	{
		super.onResume();
		
		if( ! getIntent().getBooleanExtra(Constants.INTENT_KEY_GO_NOTIFICATION_TUNNEL, false)) 
		{
			TDStockLog.d(TAG, "onSwitch");
			NotificationSwitch.getInstace().onSwitch(this);
		}
		
		
		/*if(!IS_READY_TO_CHANGE_MODE)
		{
			restoreCurrentTaskIfNeed();
		}*/


		boolean isGoingMoreActivity = this.getIntent().getBooleanExtra(Constants.INTENT_KEY_ISGO_MOREACTIVITY, false);
		boolean isSettingCurrentTabMoreActivity = this
				.getIntent()
				.getBooleanExtra(
						Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
						false);
		TDStockLog.d(TAG, "isGoingMoreActivity is" + isGoingMoreActivity);

		TDStockLog.d(TAG, "isSettingCurrentTabMoreActivity is"+ isSettingCurrentTabMoreActivity);
		String messageId = this.getIntent().getStringExtra(Constants.INTENT_KEY_MESSAGE_ID);
		String messagTypeId = this.getIntent().getStringExtra(Constants.INTENT_KEY_MESSAGE_TYPE_ID);
		TDStockLog.d(TAG, "messageId is  " + messageId);
		TDStockLog.d(TAG, "messagTypeId is  " + messagTypeId);
		if (messageId != null && !"".equals(messageId))
		{
			TDStockLog.d(TAG, String.format("message id: %s", messageId));
			Data.id = messageId;
			Data.message_type_id = messagTypeId;
			Abstract_ActivityController.IsCurrentActivity = true;
			Constants._isGo_MessageHistoryListActivity_Immediately = false;
			Constants._isGO_MessageContentActivity_Immediately = true;
		}
		else if (messageId != null && "".equals(messageId))
		{
			Abstract_ActivityController.IsCurrentActivity = true;
			Constants._isGo_MessageHistoryListActivity_Immediately = true;
			Constants._isGO_MessageContentActivity_Immediately = false;
		}
		if (isGoingMoreActivity && !isSettingCurrentTabMoreActivity)
		{
			//MoreGroup.forceToGoToRelatingTab();
			RealtimeStockActivity.SetTabIndex(4);
			TDStockLog.d(TAG, "GoingMoreActivity");
			/*Constants._isGo_MoreActivity=true;*/
		}

		if (isSettingCurrentTabMoreActivity)
		{
			/*Constants._isSettingCurructTabMoreActivity=true;*/
			if(MoreGroup.GetActivityGroupHostControl() != null)
			{
				MoreGroup.GetActivityGroupHostControl().ActivityForwardSwitch(
						this,
						MoreActivity.class,
						new Intent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NO_USER_ACTION));
				RealtimeStockActivity.SetTabIndex(4);
			}
			else
			{
				RealtimeStockActivity.SetTabIndex(4);
			}
			
			
		}

				
		   
		  
/*		  if(Constants._isGo_MoreActivity){
			 // RealtimeStockActivity.SetTabIndex(4); 
			  MoreGroup.forceToGoToRelatingTab();
		  }*/
		 /* else  if(Constants._isSettingCurructTabMoreActivity) {
			  
			  Activity  curActivity;
			   curActivity = MoreGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
			   if(curActivity !=  null) {
				   curActivity.finish();
			   }
			  MoreGroup.GetActivityGroupHostControl().ActivityEnforceSwitch(MoreActivity.class);
		  }*/
/*		  else if (Constants._isSettingCurructTabMoreActivity) {
			    Constants._isSettingCurructTabMoreActivity = false;
			    Activity  curActivity;
			   curActivity = MoreGroup.GetActivityGroupHostControl().GetHostActivity().getCurrentActivity();
				TDStockLog.d(TAG, "ready to forwarding to moreActivity!");
				MoreGroup.GetActivityGroupHostControl().ActivityFreeSwitch(curActivity, MoreActivity.class,  new Intent().addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_USER_ACTION));
			    MoreGroup.GetActivityGroupHostControl().ActivityForwardSwitch(this , MoreActivity.class, new Intent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|  Intent.FLAG_ACTIVITY_NO_USER_ACTION));
			  
			  
		  }*/
		  

//		TDStockLog.d(TAG, String.format("the current activity: %s", this
//				.getCurrentActivity().getClass().getSimpleName()));
		
		
		if(Is_Change_Mode)
		{
			setCurrentTab(isSettingCurrentTabMoreActivity);
			
			Is_Change_Mode = false;
		}
	}

	@Override
	protected void onDestroy()
	{
		TDStockLog.e(TAG, "TabActivity is dead!");

		if (StockGroup.GetActivityGroupHostControl() != null)
			StockGroup.GetActivityGroupHostControl().ResetController();
		if (MonitorGroup.GetActivityGroupHostControl() != null)
			MonitorGroup.GetActivityGroupHostControl().ResetController();
		if (IndexGroup.GetActivityGroupHostControl() != null)
			IndexGroup.GetActivityGroupHostControl().ResetController();
		if (ForeignExchangeGroup.GetActivityGroupHostControl() != null)
			ForeignExchangeGroup.GetActivityGroupHostControl().ResetController();
		if (MoreGroup.GetActivityGroupHostControl() != null)
			MoreGroup.GetActivityGroupHostControl().ResetController();
		TDStockLog.i(TAG, "All controllers have been reset");
		super.onDestroy();
	}

//	protected synchronized void genLauncher()
//	{
//		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
//				getString(R.string.app_name));
//		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
//		Intent intent2 = new Intent(Intent.ACTION_MAIN);
//		intent2.addCategory(Intent.CATEGORY_LAUNCHER);
//
//		intent2.setComponent(new ComponentName(this.getPackageName(),
//				".activity.SplashActivity"));
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
//				Intent.ShortcutIconResource.fromContext(this,
//						R.drawable.icon));
//		sendBroadcast(shortcutIntent);
//	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		
		try
		{
			CustomizeDialog.dismissAll();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return super.onOptionsItemSelected(item);
	}*/
	
	
	protected synchronized void exitAppOnHomePressed()
	{
		
//	    CdrSender sender = ((ITDLApplication) getApplicationContext()).getCdrSender();
//		if(sender != null) {
//			sender.sendCdrInfo();
//		}
		
		
		try
		{
			CustomizeDialog.dismissAll();
			disconnectLightStreamer();
			 
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		
		this.finish();
		Process.killProcess(Process.myPid());
	}
	
	

//	protected synchronized void exitApp()
//	{
//		
//		
//	    CdrSender sender = ((ITDLApplication) getApplicationContext()).getCdrSender();
//		if(sender != null) {
//			sender.sendCdrInfo();
//		}
//		
//		
//		try
//		{
//			CustomizeDialog.dismissAll();
//			disconnectLightStreamer();
//			 
//		}
//		catch (Exception e)
//		{
//			e.printStackTrace();
//		}
//		
//		
//		this.finish();
//		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
//	}

/*
 		public static void forwardToMainActivity(boolean isReadyToChangeMode,
			Context context)
	{
		if(isReadyToChangeMode)
		{
			if(INSTANCE != null)
			INSTANCE.finish();
		}
		IS_READY_TO_CHANGE_MODE = isReadyToChangeMode;
		
		Intent forwardToMainActivity = new Intent(context,
				RealtimeStockActivity.class);

		
		forwardToMainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		context.startActivity(forwardToMainActivity);
		//((ITDLApplication)(getApplicationContext())).actListController.ActivityFreeSwitch(this, iToActivityClass, iIntentObj)
		
	}
*/
	
//	@Override
//	protected void onStop()
//	{
//		super.onStop();
//		TDStockLog.d(TAG, "onStop->");
//	}
//
          @Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		TDStockLog.e(TAG, "ready to udate the intent!");
		
		TDStockLog.e(TAG, String.format("messageId=%s", intent.getStringExtra(Constants.INTENT_KEY_MESSAGE_ID)));
		
		getIntent().putExtras(intent);   //update the current intent
	}
	
	
	protected void disconnectLightStreamer()
	{
		/*LSClient	myClient = ((ITDLApplication)getApplicationContext()).getLightStreamerClient();
		((ITDLApplication)getApplicationContext()).setLightStreamerConnected(false);
			try
			{
				if (myClient != null)
{
					myClient.closeConnection();
					myClient = null;
}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}*/
	}
	

	
	/**
	 * Notes: If the user will leave the page  validly, should set the Intent.FLAG_ACTIVITY_NO_USER_ACTION FIRST;
	 * i.e. ( 	Intent intent = new Intent(getApplicationContext(), StkChartActivity.class);

		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(FinalKey.ITEMCODE, _stockCode);

		startActivity(intent);)
	 */
//	@Override
//	protected void onUserLeaveHint()
//	{
//		 TDStockLog.d(TAG,   "onUserLeaveHint!");
//		super.onUserLeaveHint();
//		
//	/*	((ITDLApplication) getApplicationContext())
//		.setExitApp(true);
//		exitAppOnHomePressed();*/
//	}
	
//	public  void onTabChanged(String tabId)
//	{
//			View curView;
//			
//			curView = tabHost.getCurrentTabView();
//			
//			if(curView == null )
//			{
//				TDStockLog.e(TAG,   "all activity destoried  belong to " + tabId );
//			}
//        	
//    }	
}
